package io.renren.modules.blog.controller;

import com.alibaba.fastjson.JSON;
import io.renren.common.utils.Result;
import io.renren.common.page.PageData;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.blog.dto.BlogArticleDto;
import io.renren.modules.blog.service.BlogArticleService;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.security.user.UserDetail;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;

import java.util.Map;

/**
 * 文章表(BlogArticle)表控制层
 *
 * @author chy
 * @since 2024-05-23 15:46:31
 */
@RestController
@AllArgsConstructor
@RequestMapping("/blogArticle")
@Api(tags = "文章表")
public class BlogArticleController {
    /**
     * 服务对象
     */
    private final BlogArticleService blogArticleService;

    /**
     * 分页查询
     *
     * @param params 筛选条件
     * @return 查询结果
     */
    @GetMapping
    public Result<PageData<BlogArticleDto>> queryByPage(@RequestParam Map<String, Object> params) {
        return new Result<PageData<BlogArticleDto>>().ok(blogArticleService.page(params));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("detail/{id}")
    public Result<BlogArticleDto> get(@PathVariable("id") Long id) {
        BlogArticleDto data = blogArticleService.get(id);
        return new Result<BlogArticleDto>().ok(data);
    }

    /**
     * 新增数据
     *
     * @param blogArticleDto 实体
     */
    @PostMapping
    public Result save(@RequestBody BlogArticleDto blogArticleDto) {
        //效验数据
        ValidatorUtils.validateEntity(blogArticleDto, AddGroup.class, DefaultGroup.class);

        UserDetail user = SecurityUser.getUser();
        blogArticleDto.setUserId(user.getId());
        blogArticleService.save(blogArticleDto);

        return new Result();
    }

    /**
     * 编辑数据
     *
     * @param blogArticleDto 实体
     */
    @PutMapping
    public Result update(@RequestBody BlogArticleDto blogArticleDto) {
        //效验数据
        ValidatorUtils.validateEntity(blogArticleDto, UpdateGroup.class, DefaultGroup.class);

        blogArticleService.update(blogArticleDto);

        return new Result();
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping("{id}")
    public Result<Boolean> deleteById(@PathVariable("id") Long id) {
        return new Result<Boolean>().ok(blogArticleService.deleteById(id));
    }

}

